package com.xiaohua.api.common.properties;

import com.xiaohua.api.domain.XhApiCredentials;
import com.xiaohua.api.service.IXhApiCredentialsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * TextIn配置属性
 *
 * @author 小花
 * @date 2025-04-01
 */
@Component
@ConfigurationProperties(prefix = "textin")
public class TextInProperties {
    
    private static final Logger log = LoggerFactory.getLogger(TextInProperties.class);
    
    private static final String TEXTIN_API_NAME = "Textin_Api";
    
    /**
     * API ID
     */
    private String appId;
    
    /**
     * API 密钥
     */
    private String secretCode;
    
    @Autowired
    private IXhApiCredentialsService apiCredentialsService;
    
    /**
     * 初始化方法，从数据库加载TextIn凭证
     */
    @PostConstruct
    public void init() {
        loadCredentialsFromDatabase();
    }
    
    /**
     * 从数据库加载凭证
     */
    public void loadCredentialsFromDatabase() {
        try {
            XhApiCredentials query = new XhApiCredentials();
            query.setApiName(TEXTIN_API_NAME);
            List<XhApiCredentials> list = apiCredentialsService.selectXhApiCredentialsList(query);
            
            if (list != null && !list.isEmpty()) {
                XhApiCredentials credential = list.get(0);
                log.info("从数据库加载TextIn API凭证");
                this.appId = credential.getApiKey();
                this.secretCode = credential.getApiSecret();
                log.info("凭证加载成功，AppId: {}", maskString(this.appId));
            } else {
                log.warn("数据库中未找到TextIn API凭证，将使用配置文件中的凭证");
            }
        } catch (Exception e) {
            log.error("从数据库加载TextIn API凭证失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 获取AppId，每次获取都检查是否需要从数据库重新加载
     */
    public String getAppId() {
        refreshCredentialsIfNeeded();
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    /**
     * 获取SecretCode，每次获取都检查是否需要从数据库重新加载
     */
    public String getSecretCode() {
        refreshCredentialsIfNeeded();
        return secretCode;
    }

    public void setSecretCode(String secretCode) {
        this.secretCode = secretCode;
    }
    
    /**
     * 如果凭证为空，刷新从数据库加载
     */
    private void refreshCredentialsIfNeeded() {
        if (appId == null || secretCode == null) {
            log.info("检测到凭证为空，从数据库重新加载");
            loadCredentialsFromDatabase();
        }
    }
    
    /**
     * 掩码显示字符串，仅显示前几个字符
     */
    private String maskString(String input) {
        if (input == null || input.length() <= 4) {
            return input;
        }
        return input.substring(0, Math.min(4, input.length())) + "********";
    }
} 